package homework.no_5;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPServer {

    public static void receiver(DatagramSocket socket){
        try {
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
            socket.receive(packet);

            System.out.println("客户端发说："+packet.getData());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        DatagramSocket socket = null;
        Scanner sc = new Scanner(System.in);
        String str = null;
        while (!"bye".equalsIgnoreCase(str)) {
            try {
                socket = new DatagramSocket();
                System.out.println("服务端请发送内容");

                str = sc.nextLine();

                byte[] bytes = str.getBytes();
                InetAddress ia = InetAddress.getByName("170.0.0.1");
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length
                        , ia, 9900);

                socket.send(packet);

                receiver(socket);

            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("欢迎下次光临!");
        socket.close();
    }
}
